<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <el-button type="primary" size="default" :icon="Plus" @click="addTrademark">增加</el-button>
    </template>
    <!-- card body -->
    <el-table style="margin-bottom: 30px" :data="tabelData" border stripe>
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="{ row }">
          <img height="60" :src="row.logoUrl" alt="" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button 
          type="warning" 
          size="default" 
          :icon="Edit" 
          @click="updateTrademark(row)">修改</el-button>
        
        <el-button type="danger" size="default" :icon="Delete" @click="deleteTrademark(row.id)">删除</el-button>
      </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:page-size="limit" v-model:current-page="page" :page-sizes="[3, 5, 7, 9]" :pager-count="5"
      layout="prev, pager, next,sizes" :total="total" />
  </el-card>


  <el-dialog v-model="dialogFormVisible" :title="newTrademark.id?'修改品牌':'新增品牌'">
    <el-form  
    :model="newTrademark"  
    :rules="trademarkRule"
    ref="ruleFormRef"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input autocomplete="off" v-model="newTrademark.tmName"/>
      </el-form-item>

      <el-form-item label="品牌Logo" prop="logoUrl">
        <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/upload`"
        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
        <img 
        v-if="newTrademark.logoUrl" 
        :src="newTrademark.logoUrl" 
        class="avatar" 
        />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrAddTrademark">确认</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script lang="ts">

import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import {ref,toRefs,onMounted,watch, reactive} from "vue"
import { Delete, Plus ,Edit} from "@element-plus/icons-vue";
import {requestTrademarkList} from "@/api/trademark"
import { ElMessage ,ElMessageBox} from 'element-plus'
import type { UploadProps,FormRules,FormInstance } from 'element-plus'
import type {reqTrademarkReturnItemType,reqAddTradeParamsType} from "@/api/trademark"
import {requestAddTrademark,requestUpdateTrademark,requestDeleteTrademark} from "@/api/trademark"
const newTrademark = ref({
  logoUrl:"",
  tmName:"",
  id:0
})


//添加上传图片的逻辑

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // newTrademark.value = URL.createObjectURL(uploadFile.raw!)
  //打印响应体
  console.log(response);
  //让响应回来的数据设置成state里面的数据
  newTrademark.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const tabelData =ref<any>([])

//页码逻辑
interface pageDateType {
  page: number;
  limit: number;
  total: number;
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 3,
  total: 100,
})
const {page, limit, total} = toRefs(pageDate.value)
//初始化时请求数据
onMounted(() => {
  getTrademarkList()
})
//1.请求数据
const getTrademarkList= async ()=>{
  const result = await requestTrademarkList({
    page: page.value,
    limit: limit.value,
  });
  //数据给state
  tabelData.value = result.records;
  total.value = result.total;
}

//监听数据页面变化发送请求
watch([page, limit],()=>{
  getTrademarkList()
})
//定义dialogFormVisible的值
const dialogFormVisible = ref(false)
//2.点击增加按钮弹出增加按钮框
const addTrademark =()=>{
    //清空上一次表单校验数据
    ruleFormRef.value?.clearValidate()

  dialogFormVisible.value = true
  //点击新增让数据变成空
  newTrademark.value={
    logoUrl:"",
    tmName:"",
    id: 0
  }
}
//设置一个域名变量
const baseUrl = import.meta.env.VITE_API_URL  
//3.点击修改弹出弹出修改框
const updateTrademark=(row:reqTrademarkReturnItemType)=>{
  //清空上一次表单校验数据
  ruleFormRef.value?.clearValidate()
  //弹出框子
  dialogFormVisible.value = true
  //然后获取数据
  newTrademark.value = {...row}
}

//获取表单form数据
const ruleFormRef = ref<FormInstance>()

//4.因为新增和删除都用的统一的弹出框，所有将点击确认写在一个逻辑里面
  const updateOrAddTrademark =async ()=>{
    //全局校验方法
    await ruleFormRef.value?.validate()
    dialogFormVisible.value= false
    try {
          //如果有id这个属性，就代表没有时点击修改的
    if(newTrademark.value.id){
        await requestUpdateTrademark(newTrademark.value)
        ElMessage.success("修改成功");

    }else{
      //如果没有id代表就是点击新增
    await   requestAddTrademark(newTrademark.value)
      //跳回当前页
    page.value = 1;
    }
    } catch (error) {
      ElMessage(newTrademark.value.id ? "修改错误" : "新增错误");
    }
    //增加或者删除之后一九重新发送拉去数据
    getTrademarkList();
  }
//删除逻辑
const deleteTrademark=(id:number)=>{
  ElMessageBox.confirm("你真的要删除吗","警告！！",{
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(async()=>{
    try {
      await requestDeleteTrademark(id)
    getTrademarkList();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  })
  .catch(()=>{
    ElMessage.info("点错了吧?");

  })
}
//表单校验逻辑
const  trademarkRule = reactive<FormRules>({
  tmName:[
    {required: true, message: "必须填写品牌名称", trigger: "blur" },
    { min: 2, max: 5, message: "长度必须是2-5", trigger: "blur" }
  ],
  logoUrl:[
    { required: true, message: "必须上传图片", trigger: "change"}
  ]
})
</script>

<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>